package org.xjtu.weteam.common.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class TokenUtils {
    private static final String SECRET_KEY = "secret_key_to_update_ids"; // 确保将此密钥保密
    private static final long EXPIRATION_TIME = 1000 * 60 * 60; // 1小时

    public static String generateToken(Integer id) {
        long now = System.currentTimeMillis();
        Date expirationDate = new Date(now + EXPIRATION_TIME);

        // 创建负载
        Map<String, Object> claims = new HashMap<>();
        claims.put("id", id);

        // 生成 token
        return Jwts.builder()
                .setClaims(claims)
                .setIssuedAt(new Date(now))
                .setExpiration(expirationDate)
                .signWith(SignatureAlgorithm.HS256, SECRET_KEY)
                .compact();
    }

    public static Integer getIdFromToken(String token) {
        try {
            Claims claims = Jwts.parser()
                    .setSigningKey(SECRET_KEY)
                    .parseClaimsJws(token)
                    .getBody();
            return claims.get("id", Integer.class); // 获取 id
        } catch (Exception e) {
            return null; // token 无效或解析失败
        }
    }

    public static boolean isOutdated(String token){
        long now = System.currentTimeMillis();
        Claims claims = Jwts.parser()
                .setSigningKey(SECRET_KEY)
                .parseClaimsJws(token)
                .getBody();

        // 检查过期时间
        Date expiration = claims.getExpiration();
        return expiration.before(new Date(now));
    }

    public static String RefreshToken(String token){

        long now = System.currentTimeMillis();
        Date expirationDate = new Date(now + EXPIRATION_TIME);
        Claims claims = Jwts.parser()
                .setSigningKey(SECRET_KEY)
                .parseClaimsJws(token)
                .getBody();
        return Jwts.builder()
                .setClaims(claims)
                .setIssuedAt(new Date(now))
                .setExpiration(expirationDate)
                .signWith(SignatureAlgorithm.HS256, SECRET_KEY)
                .compact();
    }
}
